// 存储登录历史
const SSH_HISTORY_KEY = 'webssh_history';

// DOM 元素
const loginContainer = document.getElementById('login-container');
const terminalContainer = document.getElementById('terminal-container');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const rememberCheckbox = document.getElementById('remember');
const loginBtn = document.getElementById('login-btn');
const errorMessage = document.getElementById('error-message');
const historyItems = document.getElementById('history-items');
const disconnectBtn = document.getElementById('disconnect-btn');
const clearBtn = document.getElementById('clear-btn');
const terminalElement = document.getElementById('terminal');
const statusIndicator = document.getElementById('status-indicator');
const downloadBtn = document.getElementById('download-btn');

// 初始化终端
let term;
let socket;

// 添加背景形状
function addShapes() {
    const shapes = document.querySelector('.bg-shapes');
    for (let i = 0; i < 8; i++) {
        const shape = document.createElement('div');
        shape.classList.add('shape');
        shape.classList.add(Math.random() > 0.5 ? 'shape-circle' : 'shape-square');

        const size = Math.random() * 100 + 50;
        shape.style.width = `${size}px`;
        shape.style.height = `${size}px`;
        shape.style.top = `${Math.random() * 100}%`;
        shape.style.left = `${Math.random() * 100}%`;
        shape.style.opacity = Math.random() * 0.1 + 0.03;

        shapes.appendChild(shape);
    }
}

// 加载历史记录
function loadHistory() {
    const history = JSON.parse(localStorage.getItem(SSH_HISTORY_KEY)) || [];
    historyItems.innerHTML = '';

    history.forEach(item => {
        const historyItem = document.createElement('div');
        historyItem.className = 'history-item';
        historyItem.innerHTML = `<span>${item.username}</span><small>${new Date(item.timestamp).toLocaleDateString()}</small>`;
        historyItem.addEventListener('click', () => {
            usernameInput.value = item.username;
            passwordInput.value = item.password;
            passwordInput.focus();
        });
        historyItems.appendChild(historyItem);
    });
}

// 保存历史记录
function saveHistory(username, password) {
    if (!rememberCheckbox.checked) return;

    const history = JSON.parse(localStorage.getItem(SSH_HISTORY_KEY)) || [];
    const newEntry = {
        username: username,
        password: password,
        timestamp: new Date().toISOString()
    };

    // 检查是否已存在相同记录
    const exists = history.some(item => item.username === username);

    if (!exists) {
        history.unshift(newEntry);
        // 限制历史记录数量
        if (history.length > 5) {
            history.pop();
        }
        localStorage.setItem(SSH_HISTORY_KEY, JSON.stringify(history));
        loadHistory();
    }
}

// 初始化终端
function initTerminal() {
    const isMobile = /iPhone|iPad|Android/i.test(navigator.userAgent);

    term = new Terminal({
        cursorBlink: true,
        fontSize: isMobile ? 13 : 15, // 移动端字体更小
        fontFamily: 'Fira Code, Consolas, Courier New, monospace',
        theme: {
            background: '#1e1e1e',
            foreground: '#d4d4d4',
            cursor: '#aeafad',
            selection: '#264f78',
            brightGreen: '#a7df78',
            brightYellow: '#e2e578',
            brightRed: '#ff7c7c'
        },
        letterSpacing: 0,
        lineHeight: 1.0,
        scrollback: isMobile ? 5000 : 10000, // 移动端减少滚动缓存
        screenReaderMode: false,
        disableStdin: false,
        rendererType: 'canvas',
        convertEol: true,
        allowProposedApi: true
    });

    const fitAddon = new FitAddon.FitAddon();
    term.loadAddon(fitAddon);
    term.loadAddon(new WebLinksAddon.WebLinksAddon());

    term.open(terminalElement);
    fitAddon.fit();

    // 修复文字选择和对齐问题
    const terminalScreen = document.querySelector('.xterm-screen');
    if (terminalScreen) {
        terminalScreen.style.setProperty('overflow', 'hidden', 'important');
    }

    const textLayer = document.querySelector('.xterm-text-layer');
    if (textLayer) {
        textLayer.style.setProperty('font-variant-ligatures', 'none', 'important');
        textLayer.style.setProperty('letter-spacing', 'normal', 'important');
        textLayer.style.setProperty('font-kerning', 'none', 'important');
    }

    // 移动端软键盘适配
    if (isMobile && term.textarea) {
        term.textarea.addEventListener('focus', () => {
            window.scrollTo(0, 0); // 防止输入框被键盘遮挡
        });
    }

    term.onData(data => {
        console.log('输入的数据:', data);
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify({ action: 'input', data: data }));
        }
    });

    term.onSelectionChange(() => {
        const selection = term.getSelection();
        if (selection) {
            // 处理选中文本
        }
    });

    window.addEventListener('beforeunload', () => {
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.close();
        }
    });
}

// 连接到 WebSocket 后端
function connectToServer() {
    socket = new WebSocket(`ws://${window.location.host}/ssh`);

    socket.onopen = () => {
        statusIndicator.style.backgroundColor = '#52c41a';
        term.writeln('\x1b[1;32m● 正在连接到服务器...\x1b[0m');

        // 从cookie获取token
        const token = document.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1");

        socket.send(JSON.stringify({
            action: 'connect',
            token: token
        }));
    };

    socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.type === 'output') {
            term.write(data.data);
        } else if (data.type === 'error') {
            statusIndicator.style.backgroundColor = '#ff4d4f';
            term.writeln(`\x1b[1;31m✖ 错误: ${data.message}\x1b[0m`);
        } else if (data.type === 'disconnect') {
            statusIndicator.style.backgroundColor = '#faad14';
            term.writeln('\x1b[1;33m● 连接已断开\x1b[0m');
        }
    };

    socket.onclose = () => {
        statusIndicator.style.backgroundColor = '#ff4d4f';
        term.writeln('\x1b[1;31m✖ 连接已关闭\x1b[0m');
    };

    socket.onerror = (error) => {
        statusIndicator.style.backgroundColor = '#ff4d4f';
        term.writeln(`\x1b[1;31m✖ 连接错误: ${error.message}\x1b[0m`);
    };
}

// 登录按钮点击事件
loginBtn.addEventListener('click', async () => {
    const username = usernameInput.value.trim();
    const password = passwordInput.value;

    if (!username) {
        errorMessage.textContent = '用户名不能为空';
        usernameInput.focus();
        return;
    }

    if (!password) {
        errorMessage.textContent = '密码不能为空';
        passwordInput.focus();
        return;
    }

    try {
        errorMessage.textContent = '登录中...';
        loginBtn.disabled = true;

        const response = await fetch('/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        const result = await response.json();

        if (response.ok) {
            errorMessage.textContent = '';
            saveHistory(username, password);

            // 设置token cookie
            document.cookie = `token=${result.token}; path=/; max-age=3600`; // 1小时有效期

            // 切换到终端界面
            loginContainer.style.display = 'none';
            terminalContainer.style.display = 'flex';

            // 初始化终端并连接
            initTerminal();
            connectToServer();
        } else {
            errorMessage.textContent = result.message || '登录失败';
        }
    } catch (err) {
        errorMessage.textContent = '登录请求失败，请检查网络连接';
        console.error('登录错误:', err);
    } finally {
        loginBtn.disabled = false;
    }
});

// 断开连接按钮
disconnectBtn.addEventListener('click', () => {
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.close();
    }
});

// 清屏按钮
clearBtn.addEventListener('click', () => {
    term.clear();
});

// 导出终端内容
downloadBtn.addEventListener('click', () => {
    let content = '';
    // 获取终端中的所有行
    for (let i = 0; i < term.rows; i++) {
        const line = term.buffer.active.getLine(i);
        if (line) {
            content += line.translateToString(true) + '\n';
        }
    }

    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = `terminal-output-${new Date().toISOString().slice(0, 19)}.txt`;
    document.body.appendChild(a);
    a.click();

    setTimeout(() => {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }, 100);
});

// 检查是否有保存的凭据
document.addEventListener('DOMContentLoaded', () => {
    addShapes();
    loadHistory();

    // 自动填充上次登录的用户名
    const history = JSON.parse(localStorage.getItem(SSH_HISTORY_KEY)) || [];
    if (history.length > 0) {
        usernameInput.value = history[0].username;
        passwordInput.focus();
    } else {
        usernameInput.focus();
    }
});

// 回车键登录
passwordInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        loginBtn.click();
    }
});

// Ctrl+L 清屏
document.addEventListener('keydown', (e) => {
    if ((e.ctrlKey || e.metaKey) && e.key === 'l') {
        e.preventDefault();
        term.clear();
    }
});

